<?php

defined('BASEPATH') or die('forbidden');

class Grouparea_Controller Extends Controller {
	
	private $groupList;	//用户组信息
	private $areaList;	//区信息
	private $moduleList;	//模块信息
	private $modStrategyList;	//模块策略对应表
	
    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        require_once(CONFIGPATH . 'inc.php');
        
        $sql = "SELECT *  FROM act_group ";
        $this->db->query($sql);
    	while ($n = $this->db->get_array('default')) 
    	{
            $this->groupList[$n['id']]=$n['groupname'];   
        } 
        
    	if(0 == count($this->groupList)) 
     	{
            echo "<script>alert('" . translate('C_CREATE_GROUP') . "');</script>";
        }
        
    	//区名信息
    	$sql = "SELECT *  FROM {pre}areasample ";
        $this->db->query($sql);
        //echo "sql:$sql";
    	while ($n = $this->db->get_array('default')) 
    	{
    		//print_r($n);
            $this->areaList[$n['id']]=$n['name'];   
        } 
        //print_r($this->strategyList);
    	if(0 == count($this->areaList)) 
     	{
            echo "<script>alert('" . translate('C_ADD_AREA') . "');</script>";
        }
        
        if(false == $this->getModuleList())
        {
        	return;
        }
        
    	if (false == $this->getModStrategyList()) {
        	return;
        }
    }

    function index() {
    	//print_r($this->groupList);		
        $this->view->display("activity/grouparea/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        
        //print_r($colsinfo);
        
        $rows = array();       

        $sql = "SELECT COUNT(id) AS num FROM act_group_area WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $selectSql="SELECT {$colsinfo} FROM act_group_area WHERE {$where}  ORDER BY {$sortname} {$sortorder}  LIMIT {$offset},{$rp}"; 
        $this->db->query($selectSql);      
        while ($n = $this->db->get_array('default', MYSQL_NUM)) {
        	//$n[2]=$this->inc['game_list'][$n[2]];
            $rows[] = array('id' => $n[0], 'cell' => array_values($n));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add($id = 0) {
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $selectSql="select * from act_group_area where areaid = $rowdata[areaid] ";   
            //echo $selectSql;   
			$cRow=$this->db->one($selectSql);
			if ($cRow['id']>0)
			{
				$message = " add new act_group_area error areaid:".$rowdata['areaid']."  already exists !";
				//echo $message;
				echo "<script>alert('".$message."');</script>";
				cp_tips('error', $rowdata['areaid']);
			}
			else 
			{
				$rowdata['groupname']=$this->groupList[$rowdata['groupid']];
				$rowdata['areaname']=$this->areaList[$rowdata['areaid']];
				$this->db->insert('act_group_area', $rowdata, true);
            	insert_log(translate('MENU_ACTIVITY_GROUPAREA'),translate('ADD'),null, array('groupname'=>$rowdata['groupname']));
            	//cp_tips('success', $rowdata['groupname']);
            	
				//把全部的表都通知给服务器
                $jsonData = array();
                foreach ($this->moduleList as $tableenum => $value)
                {
                	foreach ($this->modStrategyList[$tableenum] as $strategyid => $strategyname)
                	{
                		$temp = array();
                		$temp['tableenum'] = strval($tableenum);
                		$temp['tablename'] = strval($value['tablename']);
                		$temp['strategyid'] = intval($strategyid);
                		$jsonData[] = $temp;
                	}
                }
                //print_r($jsonData);
                //转成json格式数据
                $jsonData = json_encode($jsonData);
                //echo $jsonData;
                //根据区号得到地址                
                $sql = "select * from {pre}areasample where id = ".$rowdata['areaid'];
                $areaInfo = $this->db->one($sql);
                
                //发json给服务器
                $url = $areaInfo['host']."action=52&json_str=".$jsonData;
               		//echo "url = $url";
                	$ret = vpost($url);
                	
                	if (0 != $ret) {
                		echo "<script>alert('send eorr areanum:".$row['areaid']."');</script>";
                		//cp_tips("error");
                		echo " area:".$row['areaid']." send error ";
                		echo " url = $url ";
                		//echo "ret = ".$ret;
                		$isError = true;
                		break;
                	}else 
                	{
                		echo "area num:".$row['areaid']." send success ";
                	}
			}
        }else 
        {
	        $this->view->assign("areaList",$this->areaList);
	        $this->view->assign("groupList",$this->groupList);
	        $this->view->display("activity/grouparea/add");
        }
    }

    function edit($id) {
        if (!$id)
        {
            error(translate('C_INVALID_PARAM_ID', $id));
        }
        $row = $this->db->one("SELECT * FROM act_group_area WHERE id={$id}");
        if (!is_array($row))
        {
            error(translate('C_INVALID_PARAM_ID', $id));
        }
        //print_r($row);
        //exit();
        
        if (is_submit()) 
        {
            $rowdata = $_POST['row'];
            $rowdata['groupname']=$this->groupList[$rowdata['groupid']];
            //print_r($rowdata);
            //echo " id = $id ";
            $result = $this->db->update('act_group_area', $rowdata, array('id' => $id));
            //echo " result = $result ";
            if ($result) {
  
                insert_log(translate('MENU_ACTIVITY_GROUPAREA'),translate('EDIT'), $rowdata);

                //区的组变了，要把全部的表都通知给服务器
                $jsonData = array();
                foreach ($this->moduleList as $tableenum => $value)
                {
                	foreach ($this->modStrategyList[$tableenum] as $strategyid => $strategyname)
                	{
                		$temp = array();
                		$temp['tableenum'] = strval($tableenum);
                		$temp['tablename'] = strval($value['tablename']);
                		$temp['strategyid'] = $strategyid;
                		$jsonData[] = $temp;
                	}
                }
                //print_r($jsonData);
                //转成json格式数据
                $jsonData = json_encode($jsonData);
                //echo $jsonData;
                //根据区号得到地址                
                $sql = "select * from {pre}areasample where id = ".$rowdata['areaid'];
                $areaInfo = $this->db->one($sql);
                
                //发json给服务器
                $url = $areaInfo['host']."action=52&json_str=".$jsonData;
               		//echo "url = $url";
                	$ret = vpost($url);
                	
                	if (0 != $ret) {
                		echo "<script>alert('send eorr areanum:".$row['areaid']." ');</script>";
                		//cp_tips("error");
                		echo " area:".$row['areaid']." edit error ";
                		echo " url = $url ";
                		//echo "ret = ".$ret;
                		$isError = true;
                		break;
                	}else 
                	{
                		echo "area num:".$row['areaid']." edit success ";
                	}
                
                //cp_tips('success', $id);
            } else {
                //error(translate('C_TIPS_ERROR_TEXT'));
                echo " update error areanum:$row[areaid] ";
            }
        }else 
        {
	        $row=$this->db->one("select * from act_group_area where id=$id ");
	        $this->view->assign("groupList",$this->groupList);
	        $this->view->assign("areaList",$this->areaList);
	        $this->view->display("activity/grouparea/edit", array('row' => $row));
        }
    }

    function del($autoid) {
    	//echo "id = ".$autoid;
    	
        $c = 0;
        $r = '';
 
        if ($this->db->delete('act_group_area', array('id' => $autoid))) {
            insert_log(translate('MENU_ACTIVITY_GROUPAREA'),translate('DEL'), array('id'=> $autoid));
            $c = 1;
            $r = translate('C_TIPS_SUCCESS_TEXT');
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
        
    }

    function multi() {
    	
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        if (count(explode(',', $ids)) == 0) {
        	//echo " count ids = 0 ";
            $r = translate('C_INVALID_PARAMS');
        } else {
        	//echo " type = $type ";
            if ($type == 'delete') {
            	$sql = "DELETE FROM act_group_area WHERE id IN ({$ids})";
            	echo " sql = $sql ";
                $this->db->query($sql);
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
        
    }
    
	//得到模块策略信息
    function getModStrategyList()
    {
    	
    	foreach ($this->moduleList as $key => $value)
    	{
    		
	    	$sql = "SELECT *  FROM  ".$value['tablename'];
	        $this->db->query($sql);
	        //$number = 0;
	        
	        //$key 是 tableenum
	    	if ($n = $this->db->get_array('default')) 
	    	{
	    		$this->modStrategyList[$key][$n['strategyid']] = $n['strategyname'];
	    		//++$number;  	    		
	        } 
	        
	    	if(0 == count($this->modStrategyList)) 
	     	{
	            echo "<script>alert( tablename ".$value['tablename']." '" . translate('C_CREATE_TABLENAME') . "');</script>";
	            return false;
	        }
    	}
    	
    	return true;
    }

    //得到模块的信息
    function getModuleList()
    {
    	$sql = "SELECT *  FROM act_module ";
        $this->db->query($sql);
    	while ($n = $this->db->get_array('default')) 
    	{
            $this->moduleList[$n['tableenum']]['des']=$n['des']; 
            $this->moduleList[$n['tableenum']]['tablename']=$n['tablename']; 
            $this->moduleList[$n['tableenum']]['tableenum']=$n['tableenum'];   
        } 
        
    	if(0 == count($this->moduleList)) 
     	{
            echo "<script>alert('" . translate('C_CREATE_TABLENAME') . "');</script>";
            return false;
        }
        return true;
    }
}